package utils

import (
	mylog "chat/log"
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var (
	Mysql *gorm.DB
	Redis *redis.Client
)

func Init() {
	InitConfig()
	InitMysql()
	InitRedis()
}

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	err := viper.ReadInConfig()
	if err != nil {
		mylog.Error("Failed to initialize config >>>>>>> ", zap.String("error", err.Error()))
		// panic(err)
	}

	mylog.Info("config app initialized successfully >>>>> ")
}

func InitMysql() {
	var err error
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	Mysql, err = gorm.Open(mysql.Open(viper.GetString("mysql.dns")), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		mylog.Error("Failed to initialize database connection with mysql >>>>>", zap.String("error", err.Error()))
	} else {
		mylog.Info("Database connection successfully >>>>>")
	}

}

func InitRedis() {
	Redis = redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.addr"),
		DB:       viper.GetInt("redis.DB"),
		Password: viper.GetString("redis.password"),
		// PoolSize:     viper.GetInt("redis.poolSize"),
		// MinIdleConns: viper.GetInt("redis.minIdleConn"),
	})
	ctx := context.Background()
	pong, err := Redis.Ping(ctx).Result()
	if err != nil {
		mylog.Error("Redis connection error >>>> ", zap.String("error", err.Error()))

	} else {
		mylog.Info("Redis connection succeeded >>>> ")
		fmt.Printf("pong: %v\n", pong)
	}
}
